home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2605 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.4 KB

  1. Path: elroy.jpl.nasa.gov!alan
  2. From: alan@elroy.jpl.nasa.gov (Alan S. Mazer)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: why is this an infinite loop?
  5. Date: 22 Jan 1996 18:46:46 GMT
  6. Organization: Image Analysis Systems Group, JPL
  7. Message-ID: <4e0m2m$cj7@elroy.jpl.nasa.gov>
  8. References: <4dp9p5$jm2@news1.wolfe.net> <tcpnntpd.16.1.20.14.37.24.2781597121.351172@the-fix.sos.on.ca>
  9. NNTP-Posting-Host: 137.78.80.141
  10.  
  11. In article <tcpnntpd.16.1.20.14.37.24.2781597121.351172@the-fix.sos.on.ca>,
  12.  <verneb@the-fix.sos.on.ca> wrote:
  13. >To: INT:neus@wolfenet.com
  14. >
  15. >Int:neus@wolfenet.com,
  16. >
  17. >I >Beginning c student can't figure out why this small function  to read in a 
  18. >I >value for the variable x causes an infinite loop when it receives
  19. >I >unexpected 
  20. >I >input.
  21. >I >
  22. >I >double get_x()
  23. >I >{
  24. >I >int test;
  25. >I >double x;
  26. >I >
  27. >I >printf("Enter a numeric value for x: ");
  28. >I >
  29. >I >while(scanf("%lf", &x) != 1)/*could be here! change to ==1 */
  30. >I >{          
  31. >I >printf("ERROR - program expecting a number");
  32. >I >printf("Enter a numeric value for x: ");
  33. >I >}
  34.  
  35. If I understand the symptom correctly, it's because scanf doesn't remove bad
  36. input from the input stream.  So if you type "a", for example, scanf will
  37. return 0 but leave the "a" in the input stream.
  38. -- 
  39.  
  40. -- Alan                        # Mountain Dew and doughnuts...
  41.    alan@elroy.jpl.nasa.gov     # because breakfast is the most important meal
  42.                                # of the day.
  43.